package com.elock.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.dao.impl.DaoCenter;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.ExceptionUtil;
import com.elock.base.core.util.WebUtils;
import com.elock.entity.Elock;

/**
 * Dao - 锁
 * @author 仁德
 */
@Repository("elockDao")
public class ElockDao extends DaoCenter {

//	@Resource(name = "saleOrgBaseServiceImpl")
//	private SaleOrgBaseService saleOrgBaseService;

	public Page<Map<String, Object>> findPage(String elockNum, String elockName,
			Long saleOrgId, Boolean isSelect, Pageable pageable) {

		List<Object> list = new ArrayList<Object>();
		StringBuilder sql = new StringBuilder();
		Long companyInfoId = WebUtils.getCurrentCompanyInfoId();
		sql.append(
				" select e.*,sdt.value type_value,sdm.value model_value,so.name sale_org_name");
		sql.append(" from elock e left join system_dict sdt on e.type=sdt.id");
		sql.append(" left join elock_sale_org eso on e.id=eso.elock");
		sql.append(" left join sale_org so on eso.sale_org=so.id");
		sql.append(" left join system_dict sdm on e.model= sdm.id where 1=1");
		if (companyInfoId != null) {
			sql.append(" and e.company_info_id=?");
			list.add(companyInfoId);
		}
		if (!ConvertUtil.isEmpty(elockNum)) {
			sql.append(" and e.elock_number like ?");
			list.add("%" + elockNum + "%");
		}
		if (!ConvertUtil.isEmpty(elockName)) {
			sql.append(" and c.elock_name like ?");
			list.add("%" + elockName + "%");
		}
		if (saleOrgId != null) {
			sql.append(" and so.id=?");
			list.add(saleOrgId);
		}
		if (isSelect != null && isSelect) {
			sql.append(" and not exists (select 1 from elock_car where elock_id = e.id)");
		}
//		sql.append(" and so.id in (" + saleOrgBaseService.saleOrgAuth() + ")");
		sql.append(" order by e.create_date desc");

		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}

		Page<Map<String, Object>> getPage = getNativeDao().findPageMap(sql.toString(),
				objs,
				pageable);

		return getPage;

	}
	
	public Elock findByElockNum(String elockNum) {

		if (ConvertUtil.isEmpty(elockNum)) {
			ExceptionUtil.throwDaoException("value is empty!");
		}
		String sql = "select * from elock where elock_num = ?";
		Elock elock = getNativeDao().findSingleManaged(sql,
				new Object[]{elockNum},
				Elock.class);
		return elock;
	}

}